/*	This file is part of LSAC.

	LSAC is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	LSAC is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with LSAC.  If not, see <http://www.gnu.org/licenses/>.

	Copyright (c) 2010 LEPESME "Jiboo" Jean-Baptiste
*/

#include "cExpCall.h"
#include "lsac.h"

cExpCall::cExpCall(cLocation pLocation, string pLValue)
	: cExpUnary(pLocation, pLValue)
{
}

cExpCall::~cExpCall()
{
	list<cExpression*>::iterator lIterator = this->dParams.begin();
	for(; lIterator != this->dParams.end(); lIterator++)
	{
		delete (*lIterator);
	}
}

eType cExpCall::getType(cSemContext *pContext)
{
	return pContext->funcExists(this->dLValue)->dType;
}

void cExpCall::print(int pLevel)
{
	PRINT_LOG("cExpCall " << this << " " << this->dLValue);
	PRINT_LOG("{");
	list<cExpression*>::iterator lIterator = this->dParams.begin();
	for(; lIterator != this->dParams.end(); lIterator++)
	{
		(*lIterator)->print(pLevel + 1);
	}
	PRINT_LOG("}");
}

void cExpCall::validate(cSemContext *pContext)
{
	if(pContext->funcExists(this->dLValue) == NULL)
		ERROR("Erreur en " << this->dLocation << " fonction non déclaré.");

	list<cExpression*>::iterator lParamIt = this->dParams.begin();
	list<cInstDecl*>::iterator lParamDefIt = pContext->funcExists(this->dLValue)->dParams.begin();
	for(; lParamIt != this->dParams.end(); lParamIt++, lParamDefIt++)
	{
		(*lParamIt)->validate(pContext);
		eType lParamType = (*lParamDefIt)->dType;
		eType lExpType = (*lParamIt)->getType(pContext);
		if(lExpType != lParamType)
			ERROR("Erreur, parametre de type '" << lParamType << "' mais valeur de type '" << lExpType << "'.");
	}
}

void cExpCall::genCode(ostream &pStream)
{
	pStream << this->dLValue << "(";
	list<cExpression*>::iterator lIterator = this->dParams.begin();
	for(; lIterator != this->dParams.end(); lIterator++)
	{
		(*lIterator)->genCode(pStream);
		if(*lIterator != this->dParams.back())
		{
			pStream << ", ";
		}
	}
	pStream << ")";
}
